//
//  QDHomeViewController.m
//  qidianchelian
//
//  Created by 冯贺 on 2018/4/18.
//  Copyright © 2018年 冯贺. All rights reserved.
//

#import "QDHomeViewController.h"
#import "QDHomeItemView.h"
#import "QDCenterView.h"
#import <CoreLocation/CoreLocation.h>
#import "QDCityCodeModels.h"

@interface QDHomeViewController ()<CLLocationManagerDelegate>
{
    QDCenterView * centerView;
    
    CGFloat latitude;
    CGFloat longtude;
}
@property (nonatomic,strong ) CLLocationManager *locationManager;//定位服务
@property (nonatomic,copy)    NSString *currentCity;//城市
@property (nonatomic,copy)    NSString *strLatitude;//经度
@property (nonatomic,copy)    NSString *strLongitude;//维度

@property(nonatomic,strong)NSMutableArray * dataSource;
@end

@implementation QDHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSArray * titleArr = @[@"行车记录仪",@"智慧ETC",@"违章查询",@"优惠洗车"];
    NSArray * contentArr = @[@"防碰撞拍照",@"先同行后扣费",@"违章免费查询",@"待开发"];
    NSArray * imageArr = @[@"recordIcon",@"wisdomIcon",@"illegalSearch",@"washCarIcon"];
    
    UIScrollView * myScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.contentView.height)];
    myScrollView.showsVerticalScrollIndicator = NO;
    [self.contentView addSubview:myScrollView];

    UIImageView * headImage = [[UIImageView alloc]initWithFrame:CGRectMake(8, 8, SCREEN_WIDTH-16, 250*bili)];
    headImage.backgroundColor = kRedColor;
    [myScrollView addSubview:headImage];

    centerView = [[QDCenterView alloc]initWithFrame:CGRectMake(8, CGRectGetMaxY(headImage.frame)+15*bili, SCREEN_WIDTH-16, 110*bili)];
    centerView.clipsToBounds = YES;
    centerView.layer.cornerRadius = 6*bili;
    [myScrollView addSubview:centerView];
    
    CGFloat viewWidth = (SCREEN_WIDTH-24)/2;
    CGFloat viewHeight = 120*bili;
    for (int i = 0; i<4; i++) {
        
        QDHomeItemView * view = [[QDHomeItemView alloc]initWithFrame:CGRectMake(8+(viewWidth+8)*(i%2), CGRectGetMaxY(centerView.frame)+15*bili+(viewHeight+8)*(i/2), viewWidth, viewHeight)];
        [myScrollView addSubview:view];
        view.clipsToBounds = YES;
        view.layer.cornerRadius = 6*bili;
        view.titleL.text = titleArr[i];
        [view.titleL updateLayout];
        view.contentL.text = contentArr[i];
        [view.contentL updateLayout];
        view.iconImage.image = [UIImage imageNamed:imageArr[i]];

    }
    myScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, centerView.frame.origin.y+viewHeight+300*bili);
    
    [self locatemap];//定位
    
}
- (void)locatemap{
    
    if ([CLLocationManager locationServicesEnabled]) {
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        [_locationManager requestAlwaysAuthorization];
        _currentCity = [[NSString alloc]init];
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 5.0;
        [_locationManager startUpdatingLocation];
    }
}
#pragma mark - 定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    centerView.adressLabel.text = @"定位失败";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication]openURL:settingURL];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancel];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 定位成功
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    [_locationManager stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    latitude = currentLocation.coordinate.latitude;
    longtude = currentLocation.coordinate.longitude;
    [self getWeatherRequest];//天气

}
-(void)getWeatherRequest{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"lon"] = [NSString stringWithFormat:@"%f",longtude];
    params[@"lat"] = [NSString stringWithFormat:@"%f",latitude];
    params[@"key"] = WEATHER_KEY;
    params[@"format"] = @2;
    [SNHttpTool getWithZhenUrl:uGetWeatherUrl params:params View:self.contentView success:^(NSDictionary *responseDict, NSString *message) {
        NSLog(@"%@",responseDict);
        if (![message isEqualToString:@"200"]) {
            [SMGlobalMethod showMessage:@"获取天气失败"];
            return;
        }
        NSDictionary * resultDic = responseDict[@"result"];
        NSDictionary * todayDic = resultDic[@"today"];
        centerView.temperatureLabel.text = todayDic[@"temperature"];
        centerView.statusLabel.text = todayDic[@"weather"];
        centerView.washLabel.text = todayDic[@"wash_index"];
        
        centerView.dateLabel.text = [NSString stringWithFormat:@"%@  %@",todayDic[@"date_y"],todayDic[@"week"]];
        centerView.adressLabel.text = todayDic[@"city"];
        [self getCityCodeRequest];//限行
    } failure:^(NSHTTPURLResponse *error) {
    }];
    
}
-(void)getCityCodeRequest{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"key"] = Restrictions_KEY;

    [SNHttpTool getWithZhenUrl:uCityCode params:params View:self.contentView success:^(NSDictionary *responseDict, NSString *message) {
//        NSLog(@"%@",responseDict);
        NSString * error_code = [NSString stringWithFormat:@"%@",responseDict[@"error_code"]];
        if (![error_code isEqualToString:@"0"]) {
            [SMGlobalMethod showMessage:@"获取城市代码失败"];
            return;
        }
        NSArray * resultArr = responseDict[@"result"];
        self.dataSource = [QDCityCodeModels mj_objectArrayWithKeyValuesArray:resultArr];
        for (QDCityCodeModels * model in self.dataSource) {
            if ([model.cityname isEqualToString:centerView.adressLabel.text]) {
                [self getTailRestrictionsRequest:model.city];
            }
        }
    } failure:^(NSHTTPURLResponse *error) {
    }];
    
}
-(void)getTailRestrictionsRequest:(NSString *)cityCode{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"key"] = Restrictions_KEY;
    params[@"city"] = cityCode;
    
    [SNHttpTool getWithZhenUrl:uTailRestrictions params:params View:self.contentView success:^(NSDictionary *responseDict, NSString *message) {
        NSLog(@"%@",responseDict);
        NSString * error_code = [NSString stringWithFormat:@"%@",responseDict[@"error_code"]];
        if (![error_code isEqualToString:@"0"]) {
            [SMGlobalMethod showMessage:@"获取限号失败"];
            return;
        }
        NSDictionary * resultDic = responseDict[@"result"];
        NSString * isxianxing = [NSString stringWithFormat:@"%@",resultDic[@"isxianxing"]];
        if ([isxianxing isEqualToString:@"1"]) {//限行
            NSArray * xxweihao = resultDic[@"xxweihao"];
            NSLog(@"%@%@",xxweihao[0],xxweihao[1]);
            centerView.resLabel.text = [NSString stringWithFormat:@"%@ / %@",xxweihao[0],xxweihao[1]];
        }else{//不限行
            centerView.resLabel.text = @"不限";
        }
       
    } failure:^(NSHTTPURLResponse *error) {
    }];
}

-(NSMutableArray *)dataSource{
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
@end
